﻿using System.Collections.Generic;
using System.Linq;
using GC_FFW.BusinessEntities.Abstractions.Interfaces.Forecast;

namespace GC_FFW.BusinessEntities.Forecast
{
	public class Team : ITeam
	{
		#region ITeam Members

		public string Name { get; set; }

		public IEnumerable<IMatch> LastMatches { get; set; }

		public int LesionsCount
		{
			get
			{
				return LastMatches != null && LastMatches.Any()
					? LastMatches.Count(m => m.HasWinner && !m.IsTeamWin(Name))
					: 0;
			}
		}

		public int DrawsCount
		{
			get
			{
				return LastMatches != null && LastMatches.Any()
					? LastMatches.Count(m => !m.HasWinner)
					: 0;
			}
		}

		public int WinsCount
		{
			get
			{
				return LastMatches != null && LastMatches.Any()
					? LastMatches.Count(m => m.HasWinner && m.IsTeamWin(Name))
					: 0;
			}
		}

		public IMatch GetMatch(int number)
		{
			return LastMatches != null && LastMatches.Any() && number >= 1 && number <= LastMatches.Count()
				? LastMatches.OrderBy(g => g.Date).ElementAt(number - 1)
				: null;
		}

		#endregion

		#region ICloneable Members

		public object Clone()
		{
			return new Team
			{
				Name = Name != null ? Name.Clone() as string : null,
				LastMatches = LastMatches != null
					? LastMatches.Select(lm => lm.Clone() as IMatch).ToList()
					: new List<IMatch>()
			};
		}

		#endregion

		#region IUpdateTeamOperations Members

		public void UpdateName(string newName, bool? isHomeTeam = null)
		{
			var oldName = Name;

			Name = newName;

			if (LastMatches == null) return;
			foreach (var lastMatch in LastMatches)
			{
				if (lastMatch.AwayTeamName == oldName)
					lastMatch.AwayTeamName = newName;
				else if (lastMatch.HomeTeamName == oldName)
					lastMatch.HomeTeamName = newName;
			}
		}

		#endregion
	}
}
